import {
	AppWFRedirectViewActionType,
	IAppWFRedirectViewAbility,
	IAppWFRedirectViewController,
	IAppWFRedirectViewStore,
	IParam,
} from '@/core/interface';
import { router } from '@/router';
import { getIndexRoutePath } from '@/utils';
import qs from 'qs';
import { ViewController } from './view-controller';

/**
 * 应用全局流程工作重定向视图控制器
 *
 * @export
 * @class AppWFRedirectViewController
 * @extends {ViewController}
 */
export class AppWFRedirectViewController
	extends ViewController<
		AppWFRedirectViewActionType,
		IAppWFRedirectViewStore,
		IAppWFRedirectViewAbility
	>
	implements
		IAppWFRedirectViewController<
			IAppWFRedirectViewStore,
			IAppWFRedirectViewAbility
		>
{
	/**
	 * 视图加载
	 *
	 * @param {IParam} [opts={}]
	 * @return {*}
	 * @memberof IndexViewController
	 */
	public async viewMounted(opts: IParam = {}) {
		super.viewMounted(opts);
		let { srfappkey, srfappde, userTaskId } = this.store.viewParams;
		const entityDetails = App.getAppEntityConfig();
		const entity = entityDetails.find(
			(_entity: IParam) =>
				_entity.pluralizeCodeName.toLowerCase() == srfappde.toLowerCase()
		);
		if (entity) {
			const UIService = await App.getUIService(
				entity.codeName,
				this.store.context
			);
			UIService.getAppRDView(
				this.store.context,
				this.store.viewParams,
				{ [entity.codeName.toLowerCase()]: srfappkey },
				{ isEnableWorkflow: true }
			).then((response: any) => {
				if (response && response.viewName && response.srfappde) {
					const { currentRoute, push } = router;
					const indexPath = getIndexRoutePath(currentRoute.value);
					let routePath: string = `${indexPath}/${response.srfappde}/${srfappkey}/views/${response.viewName.toLowerCase()}`;
					if (userTaskId) {
						routePath = `${routePath}?${qs.stringify(
							{ taskDefinitionKey: userTaskId },
							{ delimiter: ';' }
						)}`;
					}
					push(routePath);
				} else {
					App.getNotificationHelper().error(
						App.ts('app.notificationtitle.error','错误'),
						App.ts('app.common.nofindredirected','未查找到重定向视图')
					);
				}
			});
		}
	}
}
